package com.wang.mall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mall.bean.SysMenu;
import com.wang.mall.bean.SysRoleMenu;
import com.wang.mall.mapper.SysRoleMenuMapper;
import com.wang.mall.service.SysMenuService;
import com.wang.mall.service.SysRoleMenuService;
import com.wang.mall.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysMenuService sysMenuService;

    @Override
    public List<Long> queryMenuIdList(Long roleId) {
        String roleName = sysRoleService.getById(roleId).getRoleName();
        if (roleName.equals("admin")) {
            return sysMenuService.list().stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        }
        return baseMapper.queryMenuIdList(roleId);
    }

    @Override
    public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
        //先删除角色与菜单关系
        baseMapper.deleteBatch(new Long[]{roleId});

        if (menuIdList.size() == 0) {
            return;
        }

        //保存角色与菜单关系
        for (Long menuId : menuIdList) {
            SysRoleMenu sysRoleMenuEntity = new SysRoleMenu();
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntity.setRoleId(roleId);

            this.save(sysRoleMenuEntity);
        }
    }

    @Override
    public int deleteBatch(Long[] roleIds) {
        return baseMapper.deleteBatch(roleIds);
    }


}
